package com.maserb.monitor.web.schoolStudent;

import com.alibaba.fastjson.JSONObject;
import com.maserb.monitor.common.*;
import com.maserb.monitor.entity.JwOrgEntity;
import com.maserb.monitor.entity.SysCode;
import com.maserb.monitor.entity.UserEntity;
import com.maserb.monitor.entity.schoolStudent.SchoolStudentEntity;
import com.maserb.monitor.entity.schoolStudent.StudentAchieveEntity;
import com.maserb.monitor.entity.schoolStudent.StudentScoreEntity;
import com.maserb.monitor.model.*;
import com.maserb.monitor.repository.schoolStudent.StudentAchieveRepository;
import com.maserb.monitor.service.jwEducation.JwOrgService;
import com.maserb.monitor.service.schoolStudent.SchoolStudentService;
import com.maserb.monitor.service.schoolStudent.StudentAchieveService;
import com.maserb.monitor.service.schoolStudent.StudentScoreService;
import com.maserb.monitor.service.sysCode.SysCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 学生成绩App
 */
@Controller
@RequestMapping("/studentAchieveApp")
public class StudentAchieveAppController {


    @Autowired
    StudentAchieveService achieveService;

    @Autowired
    StudentScoreService scoreService;

    @Autowired
    SysCodeService codeService;

    @Autowired
    SchoolStudentService studentService;

    @Autowired
    JwOrgService orgService;

    @Autowired
    StudentAchieveRepository studentAchieveRepository;

    /**
     * 根据成绩id查询科目分数详情
     *
     * @param achieveId
     * @return
     */
    @RequestMapping("/studentScoreList")
    @ResponseBody
    public AjaxResult<List<StudentScoreEntity>> studentScoreList(String achieveId) {
        return AjaxUtils.process(new Func_T<List<StudentScoreEntity>>() {
            @Override
            public List<StudentScoreEntity> invoke() throws Exception {
                StudentAchieveEntity achieveEntity = achieveService.findOne(achieveId);
                List<StudentScoreEntity> scoreList = scoreService.findByAchieve(achieveEntity);
                return scoreList;
            }
        });
    }

    /**
     * 返回科目列表
     *
     * @return
     */
    @RequestMapping("/getCodeList")
    @ResponseBody
    public AjaxResult<List<SysCode>> getCodeList() {
        return AjaxUtils.process(new Func_T<List<SysCode>>() {
            @Override
            public List<SysCode> invoke() throws Exception {
                List<SysCode> codeList = codeService.findByParent("SCHOOL_COURSE");
                return codeList;
            }
        });
    }


    /**
     * 查询这个班级的学生成绩
     *
     * @param clazzId 班级id
     * @return
     */
    @RequestMapping("/studentAchieveByClazzList")
    @ResponseBody
    public AjaxResult<Map<String, Object>> studentAchieveByClazzList(String startTime, String endTime, String clazzId, String codeId) {
        StringBuffer message = new StringBuffer("");
        String codeName = "";
        if (!StringUtils.isEmptyOrWhitespace(codeId)) {
            SysCode code_ex = codeService.findOne(codeId);
            codeName = code_ex.getName();
        }
        AjaxResult<Map<String, Object>> result = AjaxUtils.process(new Func_T<Map<String, Object>>() {
            @Override
            public Map<String, Object> invoke() throws Exception {
                Map<String, Object> map = new HashMap<String, Object>();
                String sysCodeName = "";
                JwOrgEntity orgEntity = orgService.findOne(clazzId);
                Double[] list = null;
                boolean isCode = false;
                SysCode code = new SysCode();
                if (StringUtils.isEmptyOrWhitespace(codeId)) {
                    list = achieveService.findAchieveByClazz(startTime, endTime, clazzId);
                } else {
                    code = codeService.findOne(codeId);
                    isCode = true;
                    sysCodeName = code.getName();
                    list = achieveService.findAchieveByClazzAndCode(startTime, endTime, clazzId, code);
                }
                List<StudentAchieveByClazzModel> modeList = new ArrayList<StudentAchieveByClazzModel>();
                if (null != list && list.length > 0) {
                    message.append("以上统计为");
                    message.append(orgEntity.getName());
                    message.append(startTime);
                    message.append("到");
                    message.append(endTime);
                    if (isCode) {
                        message.append(code.getName());
                    }
                    message.append("平均成绩分值分布饼状图，从图中可以看出");
                    StudentAchieveByClazzModel model_100 = new StudentAchieveByClazzModel("95-100分");
                    StudentAchieveByClazzModel model_95 = new StudentAchieveByClazzModel("90-95分");
                    StudentAchieveByClazzModel model_90 = new StudentAchieveByClazzModel("85-90分");
                    StudentAchieveByClazzModel model_85 = new StudentAchieveByClazzModel("80-85分");
                    StudentAchieveByClazzModel model_80 = new StudentAchieveByClazzModel("80分以下");
                    modeList.add(model_100);
                    modeList.add(model_95);
                    modeList.add(model_90);
                    modeList.add(model_85);
                    modeList.add(model_80);
                    int length = list.length;
                    for (int i = 0; i < list.length; i++) {
                        if (null != list[i]) {
                            if (list[i].compareTo(100d) <= 0 && list[i].compareTo(95d) >= 0) {
                                model_100.setCount(model_100.getCount() + 1);
                            } else if (list[i].compareTo(95d) < 0 && list[i].compareTo(90d) >= 0) {
                                model_95.setCount(model_95.getCount() + 1);
                            } else if (list[i].compareTo(90d) < 0 && list[i].compareTo(85d) >= 0) {
                                model_90.setCount(model_90.getCount() + 1);
                            } else if (list[i].compareTo(85d) < 0 && list[i].compareTo(80d) >= 0) {
                                model_85.setCount(model_85.getCount() + 1);
                            } else if (list[i].compareTo(80d) < 0) {
                                model_80.setCount(model_80.getCount() + 1);
                            }
                        }

                    }
                    /*for(StudentAchieveByClazzModel clazzModel:modeList){
                        double a = Math.round((clazzModel.getCount()*100/(double)length));
                        double d = a/100d;
                        clazzModel.setProportion(d);
                    }*/
                    Iterator iterator = modeList.iterator();
                    while (iterator.hasNext()) {
                        StudentAchieveByClazzModel clazzModel = (StudentAchieveByClazzModel) iterator.next();
                        if (clazzModel.getCount() == 0) {
                            iterator.remove();
                        } else {
                            double a = Math.round((clazzModel.getCount() * 100 / (double) length));
                            double d = a / 100d;
                            clazzModel.setProportion(d);
                            message.append(clazzModel.getScoreSegment());
                            message.append("的占");
                            message.append(clazzModel.getProportion() * 100 + "%,");
                        }
                    }
                    message.deleteCharAt(message.length() - 1);
                    message.append("。");
                    map.put("list", modeList);
                    map.put("message", message);
                    map.put("codeName", sysCodeName);
                    return map;
                } else {
                    message.append("暂无统计数据");
                    throw new Exception("暂无统计数据");
                }
            }
        });
        JSONObject extra = new JSONObject();
        extra.put("code", codeName);
        result.setExtra(extra);
        result.setMessage(message.toString());
        return result;
    }

    /**
     * 查询单个学生成绩
     *
     * @return
     */
    @RequestMapping("/studentAchieveList")
    @ResponseBody
    public AjaxResult<Map<String, Object>> studentAchieveList(String startTime, String endTime, String clazzId, String nameOrId, String codeId) {
        StringBuffer message = new StringBuffer("");
        String codeName = "";
        if (!StringUtils.isEmptyOrWhitespace(codeId)) {
            SysCode code_ex = codeService.findOne(codeId);
            codeName = code_ex.getName();
        }
        AjaxResult<Map<String, Object>> result = AjaxUtils.process(new Func_T<Map<String, Object>>() {
            @Override
            public Map<String, Object> invoke() throws Exception {
                List<SchoolStudentEntity> studentList = studentService.studentListByNameOrId(clazzId, nameOrId);
                if (null == studentList || studentList.size() < 1) {
                    message.append("暂无统计数据");
                    throw new Exception("暂无统计数据");
                }
                SchoolStudentEntity studentEntity = studentList.get(0);
                List<StudentAchieveEntity> achieveList = achieveService.findByStudentOrderByCreateTime(startTime, endTime, studentEntity.getId());

                List<StudentAchieveByCodeModel> codeModelList = new ArrayList<StudentAchieveByCodeModel>();
                if (null != achieveList && achieveList.size() > 0) {
                    /*message.append("以上统计为");
                    message.append(studentEntity.getName());
                    message.append(startTime);
                    message.append("到");
                    message.append(endTime);
                    message.append("的");*/
                    List<StudentAchieveByStudentModel> achieveModelList = new ArrayList<StudentAchieveByStudentModel>();
                    List<StudentScoreModel> studentScoreModels = new ArrayList<StudentScoreModel>();
                    for (StudentAchieveEntity achieveEntity : achieveList) {
                        if (null != achieveEntity) {
                            StudentAchieveByStudentModel achieveModel = new StudentAchieveByStudentModel();
                            if (null == achieveEntity.getAvgScore()) {
                                achieveModel.setScore(0);
                            } else {
                                achieveModel.setScore(achieveEntity.getAvgScore());
                            }
                            achieveModel.setCreateTime(CreateTimeUtils.getYearMonth(achieveEntity.getCreateTime()));
                            achieveModelList.add(achieveModel);
                            List<StudentScoreEntity> scoreEntities = scoreService.findByAchieve(achieveEntity);
                            if (null != scoreEntities && scoreEntities.size() > 0) {
                                for (StudentScoreEntity scoreEntity : scoreEntities) {
                                    StudentScoreModel scoreModel = new StudentScoreModel();
                                    scoreModel.setCodeId(scoreEntity.getSubject().getId());
                                    scoreModel.setCodeName(scoreEntity.getSubject().getName());
                                    scoreModel.setCreateTime(achieveEntity.getCreateTime());
                                    scoreModel.setScore(scoreEntity.getScore());
                                    studentScoreModels.add(scoreModel);
                                }
                            }
                        }

                    }
                    StudentAchieveByCodeModel achieveByCodeModel = new StudentAchieveByCodeModel();
                    achieveByCodeModel.setName("平均分");
                    achieveByCodeModel.setScoreList(achieveModelList);
                    codeModelList.add(achieveByCodeModel);
                    List<String> xAxis_avg = new ArrayList<String>();
                    List<StudentAchieveByStudentModel> byStudentModelList_avg = achieveByCodeModel.getScoreList();
                    for (StudentAchieveByStudentModel achieveByStudentModel : byStudentModelList_avg) {
                        xAxis_avg.add(achieveByStudentModel.getCreateTime());
                    }
                    List<SysCode> codeList = codeService.findByParent("SCHOOL_COURSE");
                    if (null != codeList && codeList.size() > 0) {
                        for (SysCode code : codeList) {
                            List<StudentAchieveByStudentModel> studentAchieveByStudentModel = new ArrayList<StudentAchieveByStudentModel>();
                            for (StudentScoreModel scoreModel : studentScoreModels) {
                                if (code.getId().equals(scoreModel.getCodeId())) {
                                    StudentAchieveByStudentModel studentModel = new StudentAchieveByStudentModel();
                                    studentModel.setCreateTime(CreateTimeUtils.getYearMonth(scoreModel.getCreateTime()));
                                    studentModel.setScore(scoreModel.getScore());
                                    studentAchieveByStudentModel.add(studentModel);
                                }
                            }
                            if (null != studentAchieveByStudentModel && studentAchieveByStudentModel.size() > 0) {
                                StudentAchieveByCodeModel achieveByCodeModel_code = new StudentAchieveByCodeModel();
                                achieveByCodeModel_code.setName(code.getName());
                                achieveByCodeModel_code.setScoreList(studentAchieveByStudentModel);
                                codeModelList.add(achieveByCodeModel_code);
                            }
                        }
                    }
                    if (!StringUtils.isEmptyOrWhitespace(codeId)) {
                        SysCode syscode = codeService.findOne(codeId);
                        /*List<StudentAchieveByStudentModel> studentAchieveByStudentModel_code = stringListMap.get(syscode.getCode());
                        Map<String,List<StudentAchieveByStudentModel>> stringListMap_code = new HashMap<String,List<StudentAchieveByStudentModel>>();
                        stringListMap_code.put(syscode.getCode(),studentAchieveByStudentModel_code);*/
                        List<StudentAchieveByCodeModel> codeModelList_code = new ArrayList<StudentAchieveByCodeModel>();
                        List<String> xAxis = new ArrayList<String>();
                        for (StudentAchieveByCodeModel byCodeModel : codeModelList) {
                            if (syscode.getName().equals(byCodeModel.getName())) {
                                codeModelList_code.add(byCodeModel);
                                List<StudentAchieveByStudentModel> byStudentModelList = byCodeModel.getScoreList();
                                for (StudentAchieveByStudentModel achieveByStudentModel : byStudentModelList) {
                                    xAxis.add(achieveByStudentModel.getCreateTime());
                                }
                            }
                        }
                        Map<String, Object> codeMap = new HashMap<String, Object>();
                        codeMap.put("list", codeModelList_code);
                        codeMap.put("xAxis", xAxis);
                        codeMap.put("maxScore", 100);
                        /*message.append(syscode.getName());
                        message.append("成绩分布折现图，从图中可以看出..................................................");*/
                        return codeMap;
                        // return stringListMap_code;

                    } else {
                        message.append("成绩分布折现图，从图中可以看出..................................................");
                        Map<String, Object> achieveMap = new HashMap<String, Object>();
                        achieveMap.put("list", codeModelList);
                        achieveMap.put("xAxis", xAxis_avg);
                        achieveMap.put("maxScore", 100);
                        return achieveMap;
                    }
                } else {
                    message.append("暂无统计数据");
                    throw new Exception("暂无统计数据");
                }
            }
        });
        JSONObject extra = new JSONObject();
        extra.put("code", codeName);
        result.setExtra(extra);
        //result.setMessage(message.toString());
        return result;
    }


    @RequestMapping("/getMessageList")
    @ResponseBody
    public AjaxResult<List<JpushMessageModel>> getMessageList(String username, int count, String begin_time, String end_time) {
        return AjaxUtils.process(new Func_T<List<JpushMessageModel>>() {
            @Override
            public List<JpushMessageModel> invoke() throws Exception {
                List<JpushMessageModel> modelList = new ArrayList<JpushMessageModel>();
                modelList = JpushImClientUtil.getUserMessages(username, count, begin_time, end_time);
                return modelList;
            }
        });
    }

    /**
     * 获取学生成绩（通过学生id，考试期数id）
     *
     * @param request
     * @param studentId
     * @param achieveId
     * @return
     */
    @RequestMapping("/getStudentAchieve")
    public ModelAndView getStudentAchieve(final HttpServletRequest request, String studentId, String achieveId) {
        ModelAndView view = new ModelAndView();
        view.setViewName("student_achieve/student_score");
        SchoolStudentEntity studentEntity = new SchoolStudentEntity();
        try {
            studentEntity = studentService.findOne(studentId);
        } catch (Exception e) {
            view.setViewName("student_achieve/student_not_score");
            return view;
        }
        //学生信息
        if (null == studentEntity) {
            view.setViewName("student_achieve/student_not_score");
            return view;
        }
        //考试期数
        List<StudentAchieveEntity> achieveEntityList = achieveService.findByStudentByCreateTime(studentEntity);
        if (null == achieveEntityList && achieveEntityList.size() < 1) {
            view.setViewName("student_achieve/student_not_score");
            return view;
        }

        //各科分数
        List<StudentScoreEntity> studentScoreEntityList = new ArrayList<StudentScoreEntity>();
        //当前考试期数详情
        StudentAchieveEntity achieveEntity = new StudentAchieveEntity();
        if (StringUtils.isEmptyOrWhitespace(achieveId)) {
            if (achieveEntityList.size() > 0) {
                achieveEntity = achieveEntityList.get(0);
                studentScoreEntityList = scoreService.findByAchieveOrderByScoreDesc(achieveEntity);
            } else {
                view.setViewName("student_achieve/student_not_score");
                return view;
            }
        } else {
            achieveEntity = achieveService.findOne(achieveId);
            studentScoreEntityList = scoreService.findByAchieveOrderByScoreDesc(achieveEntity);
        }
        if (null == studentScoreEntityList || studentScoreEntityList.size() < 1) {
            view.setViewName("student_achieve/student_not_score");
            return view;
        }
        //最高分
        StudentScoreEntity scoreHighEntity = new StudentScoreEntity();
        //最低分
        StudentScoreEntity scoreLowEntity = new StudentScoreEntity();
        if (studentScoreEntityList.size() > 0) {
            scoreHighEntity = studentScoreEntityList.get(0);
            scoreLowEntity = studentScoreEntityList.get(studentScoreEntityList.size() - 1);
        }
        //班级每科平均成绩
        List<StudentClazzScoreModel> clazzScoreModelList = new ArrayList<StudentClazzScoreModel>();
        for (StudentScoreEntity scoreEntity : studentScoreEntityList) {
            StudentClazzScoreModel model = new StudentClazzScoreModel();
            Double d = studentAchieveRepository.findAchieveByClazzAndCodeAndAchieve(studentEntity.getOrgId(), achieveEntity.getTerm(), scoreEntity.getSubject());
            d = (double) Math.round(d * 10) / 10;
            model.setCodeName(scoreEntity.getSubject().getName());
            model.setAvgScore(d);
            clazzScoreModelList.add(model);
        }
        //班级排名
        List<StudentAchieveEntity> achieveEntities = new ArrayList<StudentAchieveEntity>();
        int classRank = 0;
        int cityRank = 0;
        if (null != achieveEntity.getCityRank()) {
            cityRank = achieveEntity.getCityRank();
        }
        if (null != achieveEntity.getClazzRank()) {
            classRank = achieveEntity.getClazzRank();
        } else {
            if (null != achieveEntity) {
                achieveEntities = achieveService.findAchieveByClazzOrderByTotalScoreDesc(achieveEntity.getClazzId(), achieveEntity.getTerm());
                if (achieveEntities.size() > 0) {
                    for (int i = 0; i < achieveEntities.size(); i++) {
                        if (achieveEntities.get(i).equals(achieveEntity)) {
                            classRank = i + 1;
                        }
                    }
                }
            }
        }
        String[] scoreArr = new String[studentScoreEntityList.size()];
        Double countScore = 0d;
        for (int i = 0; i < studentScoreEntityList.size(); i++) {
            scoreArr[i] = studentScoreEntityList.get(i).getSubject().getName();
            countScore += studentScoreEntityList.get(i).getScore();
        }
        for (StudentAchieveEntity studentAchieveEntity : achieveEntityList) {
            studentAchieveEntity.setStudent(null);
        }
        for (StudentScoreEntity scoreEntity : studentScoreEntityList) {
            scoreEntity.setAchieve(null);
        }
        view.addObject("studentId", studentId);
        view.addObject("achieveId", achieveEntity.getId());
        view.addObject("achieveEntityList", achieveEntityList);
        view.addObject("achieveEntity", achieveEntity);
        view.addObject("studentEntity", studentEntity);
        view.addObject("clazzScoreModelList", clazzScoreModelList);
        view.addObject("studentScoreEntityList", studentScoreEntityList);
        view.addObject("scoreHighEntity", scoreHighEntity);
        view.addObject("scoreLowEntity", scoreLowEntity);
        view.addObject("achieveEntities", achieveEntities);
        view.addObject("classRank", classRank);
        view.addObject("cityRank", cityRank);
        view.addObject("countScore", countScore);
        /*  view.addObject("achieveEntity",achieveEntity);*/
        return view;
    }

    @RequestMapping("/getClassAchieve")
    public ModelAndView getClassAchieve(final HttpServletRequest request, String classId, String userId, String achieveId) {
        ModelAndView view = new ModelAndView();
        view.setViewName("student_achieve/class_score");

        return view;
    }
}
